<template>
  <div class="user-profile">
    <el-card class="profile-card">
      <template #header>
        <div class="card-header">
          <span>个人信息</span>
          <el-button type="primary" @click="handleEdit" v-if="!isEditing">编辑</el-button>
        </div>
      </template>

      <el-form
        ref="formRef"
        :model="userForm"
        :rules="rules"
        label-width="100px"
        :disabled="!isEditing"
        class="profile-form">
        <el-form-item label="头像">
          <el-upload
            class="avatar-uploader"
            action="/api/upload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            :disabled="!isEditing">
            <img v-if="userForm.avatar" :src="userForm.avatar" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>

        <el-form-item label="用户名" prop="username">
          <el-input v-model="userForm.username" placeholder="请输入用户名" />
        </el-form-item>

        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="userForm.nickname" placeholder="请输入昵称" />
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userForm.email" placeholder="请输入邮箱" />
        </el-form-item>

        <el-form-item label="手机号" prop="phone">
          <el-input v-model="userForm.phone" placeholder="请输入手机号" />
        </el-form-item>

        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="userForm.gender">
            <el-radio label="male">男</el-radio>
            <el-radio label="female">女</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="个人简介" prop="bio">
          <el-input
            v-model="userForm.bio"
            type="textarea"
            :rows="4"
            placeholder="请输入个人简介"
          />
        </el-form-item>

        <el-form-item v-if="isEditing">
          <el-button type="primary" @click="handleSave">保存</el-button>
          <el-button @click="handleCancel">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- <el-card class="security-card">
      <template #header>
        <div class="card-header">
          <span>安全设置</span>
        </div>
      </template>

      <el-form label-width="120px" class="security-form">
        <el-form-item label="修改密码">
          <el-button type="primary" @click="showChangePassword = true">
            修改密码
          </el-button>
        </el-form-item>

        <el-form-item label="账号安全">
          <el-button type="primary" @click="showSecuritySettings = true">
            安全设置
          </el-button>
        </el-form-item>
        
        <el-form-item label="退出登录">
          <el-button type="danger" @click="handleLogout">
            退出登录
          </el-button>
        </el-form-item>
      </el-form>
    </el-card> -->

    <!-- 修改密码对话框 -->
    <!-- <el-dialog
      v-model="showChangePassword"
      title="修改密码"
      width="400px">
      <el-form
        ref="passwordFormRef"
        :model="passwordForm"
        :rules="passwordRules"
        label-width="100px">
        <el-form-item label="当前密码" prop="currentPassword">
          <el-input
            v-model="passwordForm.currentPassword"
            type="password"
            placeholder="请输入当前密码"
            show-password
          />
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input
            v-model="passwordForm.newPassword"
            type="password"
            placeholder="请输入新密码"
            show-password
          />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
            v-model="passwordForm.confirmPassword"
            type="password"
            placeholder="请再次输入新密码"
            show-password
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showChangePassword = false">取消</el-button>
          <el-button type="primary" @click="handleChangePassword">
            确认修改
          </el-button>
        </span>
      </template>
    </el-dialog> -->

    <!-- 安全设置对话框 -->
    <!-- <el-dialog
      v-model="showSecuritySettings"
      title="安全设置"
      width="500px">
      <el-form label-width="120px">
        <el-form-item label="登录密码">
          <el-switch v-model="securitySettings.passwordLogin" />
        </el-form-item>
        <el-form-item label="手机验证码">
          <el-switch v-model="securitySettings.smsLogin" />
        </el-form-item>
        <el-form-item label="邮箱验证码">
          <el-switch v-model="securitySettings.emailLogin" />
        </el-form-item>
        <el-form-item label="登录通知">
          <el-switch v-model="securitySettings.loginNotification" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showSecuritySettings = false">取消</el-button>
          <el-button type="primary" @click="handleSaveSecuritySettings">
            保存设置
          </el-button>
        </span>
      </template>
    </el-dialog> -->
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import { getCurrentUser, updateUserInfo, changePassword, updateSecuritySettings } from '../api/user'

const isEditing = ref(false)
const showChangePassword = ref(false)
const showSecuritySettings = ref(false)
const formRef = ref(null)
const passwordFormRef = ref(null)
const router = useRouter()

// 用户信息表单数据
const userForm = reactive({
  avatar: '',
  username: '',
  nickname: '',
  email: '',
  phone: '',
  gender: 'male',
  bio: ''
})

// 原始用户数据，用于取消编辑时恢复
const originalUserData = ref({})

const passwordForm = reactive({
  currentPassword: '',
  newPassword: '',
  confirmPassword: ''
})

const securitySettings = reactive({
  passwordLogin: true,
  smsLogin: false,
  emailLogin: false,
  loginNotification: true
})

const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  nickname: [
    { required: true, message: '请输入昵称', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ]
}

const passwordRules = {
  currentPassword: [
    { required: true, message: '请输入当前密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== passwordForm.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

const handleEdit = () => {
  isEditing.value = true
}

const handleSave = async () => {
  if (!formRef.value) return
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const data = await updateUserInfo({
          nickname: userForm.nickname,
          email: userForm.email,
          phone: userForm.phone,
          gender: userForm.gender,
          bio: userForm.bio,
          avatar: userForm.avatar
        })
        
        if (data.code === 200) {
          ElMessage.success('保存成功')
          // 更新本地存储的用户信息
          const user = JSON.parse(localStorage.getItem('user') || '{}')
          Object.assign(user, {
            nickname: userForm.nickname,
            email: userForm.email,
            phone: userForm.phone,
            gender: userForm.gender,
            bio: userForm.bio,
            avatar: userForm.avatar
          })
          localStorage.setItem('user', JSON.stringify(user))
          
          // 更新原始数据
          Object.assign(originalUserData.value, userForm)
          isEditing.value = false
        } else {
          ElMessage.error(data.message || '保存失败')
        }
      } catch (error) {
        console.error('保存用户信息错误:', error)
        ElMessage.error('保存失败，请稍后重试')
      }
    }
  })
}

const handleCancel = () => {
  isEditing.value = false
  // 恢复原始数据
  Object.assign(userForm, originalUserData.value)
}

const handleAvatarSuccess = (response) => {
  userForm.avatar = response.url
}

const beforeAvatarUpload = (file) => {
  const isJPG = file.type === 'image/jpeg'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPG) {
    ElMessage.error('上传头像图片只能是 JPG 格式!')
  }
  if (!isLt2M) {
    ElMessage.error('上传头像图片大小不能超过 2MB!')
  }
  return isJPG && isLt2M
}

const handleChangePassword = async () => {
  if (!passwordFormRef.value) return
  await passwordFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const data = await changePassword({
          currentPassword: passwordForm.currentPassword,
          newPassword: passwordForm.newPassword
        })
        
        if (data.code === 200) {
          ElMessage.success('密码修改成功')
          showChangePassword.value = false
          // 重置密码表单
          passwordForm.currentPassword = ''
          passwordForm.newPassword = ''
          passwordForm.confirmPassword = ''
        } else {
          ElMessage.error(data.message || '密码修改失败')
        }
      } catch (error) {
        console.error('修改密码错误:', error)
        ElMessage.error('密码修改失败，请稍后重试')
      }
    }
  })
}

const handleSaveSecuritySettings = async () => {
  try {
    const data = await updateSecuritySettings(securitySettings)
    
    if (data.code === 200) {
      ElMessage.success('安全设置保存成功')
      showSecuritySettings.value = false
    } else {
      ElMessage.error(data.message || '保存安全设置失败')
    }
  } catch (error) {
    console.error('保存安全设置错误:', error)
    ElMessage.error('保存安全设置失败，请稍后重试')
  }
}

const handleLogout = () => {
  // 清除本地存储的用户信息和token
  localStorage.removeItem('user')
  localStorage.removeItem('token')
  
  // 显示退出成功消息
  ElMessage.success('退出登录成功')
  
  // 重定向到登录页面
  router.push('/login')
}

// 在组件挂载时获取用户信息
onMounted(async () => {
  try {
    // 检查token是否存在
    const token = localStorage.getItem('token')
    if (!token) {
      ElMessage.warning('您尚未登录，请先登录')
      router.push('/login')
      return
    }
    
    // 尝试从本地存储获取用户信息
    const userStorage = localStorage.getItem('user')
    if (userStorage) {
      const userData = JSON.parse(userStorage)
      Object.assign(userForm, userData)
      Object.assign(originalUserData.value, userData)
    }
    
    // 从服务器获取最新用户信息
    const data = await getCurrentUser()
    if (data.code === 200) {
      // 更新表单数据
      Object.assign(userForm, data.data)
      // 保存原始数据，用于取消编辑时恢复
      Object.assign(originalUserData.value, data.data)
      // 更新本地存储
      localStorage.setItem('user', JSON.stringify(data.data))
    } else if (data.code === 401) {
      // 未登录或token无效，跳转到登录页面
      ElMessage.warning(data.message || '您尚未登录，请先登录')
      router.push('/login')
    } else {
      ElMessage.warning('获取用户信息失败，显示本地缓存数据')
    }
  } catch (error) {
    console.error('获取用户信息错误:', error)
    ElMessage.warning('获取用户信息失败，显示本地缓存数据')
  }
})
</script>

<style scoped>
.user-profile {
  padding: 20px;
  display: grid;
  grid-template-columns: 1fr;
  gap: 20px;
}

.profile-card,
.security-card {
  background-color: #ffffff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.profile-form {
  max-width: 600px;
  margin: 0 auto;
}

.avatar-uploader {
  text-align: center;
}

.avatar-uploader .avatar {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  object-fit: cover;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 50%;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: #67C23A;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  text-align: center;
  line-height: 100px;
}

.security-form {
  max-width: 400px;
}

:deep(.el-form-item__label) {
  color: #606266;
}

:deep(.el-input__wrapper) {
  box-shadow: 0 0 0 1px #dcdfe6 inset;
}

:deep(.el-input__wrapper:hover) {
  box-shadow: 0 0 0 1px #67C23A inset;
}

:deep(.el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 1px #67C23A inset;
}

:deep(.el-button--primary) {
  background-color: #67C23A;
  border-color: #67C23A;
}

:deep(.el-button--primary:hover) {
  background-color: #85ce61;
  border-color: #85ce61;
}

:deep(.el-radio__input.is-checked .el-radio__inner) {
  background-color: #67C23A;
  border-color: #67C23A;
}

:deep(.el-switch.is-checked) {
  background-color: #67C23A;
}
</style>